from marshmallow import fields
from applications.models import User
from applications.models import Hospital
from applications.models import Equipment
from applications.models import Record
from applications.extensions import ma
import json


# 用户models的序列化类
class RecordOutSchema(ma.Schema):
    id = fields.Integer()
    hospital_no = fields.Str()
    hospital = fields.Method("get_hospital_name")
    device_no = fields.Str()
    device = fields.Method("get_device_name")
    cc = fields.Method("get_record_num")
    name = fields.Str()
    username = fields.Str()
    adminname = fields.Method("get_usernames")
    case_no = fields.Str()
    cts = fields.Method("get_cts_dicts")
    u6 = fields.Method("get_u6")
    mir = fields.Method("get_mir")
    type = fields.Integer()
    create_time = fields.DateTime()
    results = fields.Decimal()
    random = fields.Str()
    id_card = fields.Str()
    test_time = fields.Method("get_test_time")
    sex = fields.Integer()
    dow_count = fields.Integer()
    states = fields.Str()
    exception = fields.Str()

    @staticmethod
    def get_test_time(obj):
        if obj and obj.test_time is not None:
            t = obj.test_time.strftime("%Y-%m-%d %H:%M")
            return t
        else:
            return None

    @staticmethod
    def get_usernames(obj):
        if obj and obj.user_id is not None:
            return User.query.filter_by(id=obj.user_id).first().username
        else:
            return None

    @staticmethod
    def get_hospital_name(obj):
        if obj and obj.hospital_no is not None:
            hospital = Hospital.query.filter_by(hospital_no=obj.hospital_no).first()
            if hospital is not None:
                return Hospital.query.filter_by(hospital_no=obj.hospital_no).first().name
            else:
                return None
        else:
            return None

    @staticmethod
    def get_device_name(obj):
        if obj and obj.device_no is not None:
            device = Equipment.query.filter_by(device_no=obj.device_no).first()
            if device is not None:
                return Equipment.query.filter_by(device_no=obj.device_no).first().name
            else:
                return None
        else:
            return None

    @staticmethod
    def get_record_num(obj):
        if obj and obj.random is not None:
            return Record.query.filter_by(random=obj.random).count()
        else:
            return None

    @staticmethod
    def get_mir(obj):
        if obj and obj.cts != None:
            return json.loads(obj.cts)['mir']
        else:
            return {}

    @staticmethod
    def get_u6(obj):
        if obj and obj.cts is not None:
            return json.loads(obj.cts)['u6']
        else:
            return {}


    @staticmethod
    def get_cts_dicts(obj):
        if obj and obj.cts is not None:
            return json.loads(obj.cts)
        else:
            return {}
